package com.hay.elasticsearch.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hay.elasticsearch.pojo.Goods;
import com.hay.elasticsearch.repository.GoodsReponsitory;
import com.hay.elasticsearch.service.SearchService;
import com.hay.item.api.GoodsApi;
import com.hay.item.pojo.Spu;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @title: GoodsListener
 * @Author HuangYan
 * @Date: 2020/7/31 17:47
 * @Version 1.0
 */
@Component
public class GoodsListener {

    @Autowired
    private SearchService searchService;

    @Autowired
    private GoodsApi goodsApi;

    @Autowired
    private GoodsReponsitory goodsReponsitory;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "LEYOU.SEARCH.SAVE.QUEUE", durable = "true", ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(value = "LEYOU.ITEM.EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = {"leyou.item.insert", "leyou.item.update"}
    ))
    public void save(Long id) throws JsonProcessingException {
        if (id == null){
            return;
        }
        Spu spu = goodsApi.querySpuById(id);
        Goods goods = searchService.buildGoods(spu);
        goodsReponsitory.save(goods);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "LEYOU.SEARCH.DELETE.QUEUE", durable = "true", ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(value = "LEYOU.ITEM.EXCHANGE", ignoreDeclarationExceptions = "true"),
            key = {"leyou.item.delete"}
    ))
    public void delete(Long id) throws JsonProcessingException {
        if (id == null){
            return;
        }
        Spu spu = goodsApi.querySpuById(id);
        Goods goods = searchService.buildGoods(spu);
        goodsReponsitory.delete(goods);
    }

}
